"use strict";

var app = angular.module('boardManagementApp', ['angularFileUpload', 'angularUtils.directives.dirPagination'])
  .directive('showErrors', crabii.validation_directive);

app.controller('boardManagementController', function($scope, $http, FileUploader) {
  var $ = jQuery;
  var settings = Drupal.settings;

  $scope.boards = [];
  $scope.boards_count = 0;
  $scope.boards_per_page = settings.board_management.boards_per_page;
  $scope.boards_selected = [];
  $scope.category_options = settings.board_management.category_options

  var get_url = '/cpanel/board-management/get';
  var post_url = '/board/' + settings.board_management.uid  + '/post';
  var update_url = '/cpanel/board-management/update';
  var delete_url = '/cpanel/board-management/delete';
  var token = settings.board_management.token;
  var current_page = 1;

  // uploader object
  var uploader = $scope.uploader = new FileUploader({
    url: post_url,
    queueLimit: 1,
    removeAfterUpload: true,
    alias: 'files[file]'
  });

  /**
   * get nips from remote url
   */
  function get_results_page(page_number) {
    current_page = page_number;
    if(page_number > 0) {
      page_number--; // drupal start page number from 0
    }

    $http.get(get_url + '?page=' + page_number + '&user_board_token=' + token)
      .success(function (data) {
        $scope.boards = data['boards'];
        $scope.boards_count = data['count'];
      });
  }

  $scope.delete_boards = function() {
    $http({
      method: 'POST',
      url: delete_url,
      data: jQuery.param({boards_selected: $scope.boards_selected, user_board_token: token}),
      headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
    })
      .success(function (data) {
        $scope.reset();
        $('.modal').modal('hide');
      });
  }

  $scope.delete_board = function(board) {
    $scope.boards_selected = [];
    $('.checkbox-board').prop('checked', false);
    $scope.boards_selected.push(board);
  }

  $scope.update_board = function(board) {
    $scope.board = board;
    $scope.board.user_board_token = token;
  }

  $scope.bulk_actions_enabled = function() {
    return $scope.boards_selected.length > 0
  }

  $scope.page_changed = function(new_page) {
    get_results_page(new_page);
  };

  $scope.reset = function(no_reload) {
    $scope.$broadcast('crabii-show-errors-reset');

    if(typeof no_reload == 'undefined') {
      get_results_page(1);
    }
    else {
      if(no_reload == false) {
        get_results_page(1);
      }
    }

    $scope.board = $.extend(true, {}, settings.board_management.board); // clone the object

    setTimeout(function() {$('.checkbox-all').prop('checked', false).trigger('change');}, 500)
  }

  /**
   *  helper function for collecting form data
   */
  function getFormData() {
    return {
      tid: $scope.board.tid,
      name: $scope.board.name,
      category: $scope.board.field_category.und[0].value,
      privacy: $scope.board.field_privacy.und[0].value,
      user_board_token: token
    }
  }

  /**
   * creating boards handler
   */
  $scope.createBoards = function () {
    $scope.$broadcast('crabii-show-errors-check-validity');

    $scope.showErrorsCheckValidity = true;

    if (!$scope.userBoardForm.$valid) {
      return;
    }

    $('#user-board-form button').prop('disabled', true);
    if(uploader.queue.length > 0) {
      uploader.uploadAll();
    } else {
      $http({
        method: 'POST',
        url: post_url,
        data: jQuery.param(getFormData()),
        headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
      }).success(function (data) {
        afterBoardCreation(data);
      });
    }
  }

  /**
   * fire after successfully submit the form
   */
  function afterBoardCreation(data) {
    $('#user-board-form button').prop('disabled', false);
    var errors = data.errors || [];
    if(errors.length > 0) {
      var errors = '<ul class="list-unstyled">';
      angular.forEach(data.errors, function(value, key) {
        errors += '<li>' + value + '</li>';
      });
      errors += '</ul>';
      $('.user-board-errors').append(errors);
    } else {
      $scope.reset();
      setTimeout(function() {$('.modal').modal('hide');}, 500);
    }
  }

  // CALLBACKS
  uploader.onBeforeUploadItem = function(item) {
    var formData = [getFormData()];
    Array.prototype.push.apply(item.formData, formData);
  };
  uploader.onCompleteItem = function(item, response, status, headers) {
    afterBoardCreation(response);
  }

  $scope.reset();
});

/**
 * handling checkboxes since there's no easy way to do that in angular
 */
jQuery(document).ready(function($) {
  var $scope = angular.element('.cpanel-board-management').scope(); // get $scope

  $('.checkbox-all', '.cpanel-board-management').change(function () {
    $scope.$apply(function() {
      $scope.boards_selected = [];
    });
    $('.checkbox-board').prop('checked', $(this).prop('checked')).trigger('change');
  });

  $('.cpanel-board-management').on('change', '.checkbox-board', function() {
    var $this = $(this);
    var val = $this.val();
    var boards_selected = $scope.boards_selected;

    if($this.prop('checked')) {
      $.each($scope.boards, function(index, board) {
        if(val == board.tid) {
          boards_selected.push($scope.boards[index]);
          return false;
        }
      });
    }
    else {
      // find index
      $.each(boards_selected, function(index, board) {
        if(board.tid == val) {
          boards_selected.splice(index, 1);
          return false;
        }
      });
    }

    $scope.$apply(function() {
      $scope.boards_selected = boards_selected;
    });
  });

  // reset
  $('#user-board-form').on('hidden.bs.modal', function(){
    $scope.$apply(function() {
      $scope.reset();
    });
  });
});
